<?php

namespace Yolo\Tests;

use Exception;
use GuzzleHttp\Client;
use Hyperf\Guzzle\CoroutineHandler;
use GuzzleHttp\HandlerStack;
use Psr\Http\Message\ResponseInterface;
use Yolo\Config\Config;
use Yolo\Di\DI;

/**
 * RPCClient
 * @author lushaoming<lushaoming6@gmail.com>
 * @date 2024/1/26
 */
class RpcClient
{

    private Client $client;


    public function __construct(string $service)
    {
        $url = DI::use(Config::class)->getClientConnection($service);
        if (empty($url)) {
            throw new Exception("rpc.clients.$service does not exist.", -1);
        }

        $this->client = new Client([
            'base_uri' => $url,
            'handler' => HandlerStack::create(new CoroutineHandler()),
            'timeout' => 10,
        ]);
    }

    public function invokeByNs(string $service, string $ns, string $api, array $args, array $metadata): ResponseInterface
    {
        if ($ns === '' || $ns === 'Api') {
            $endpoint = "$service.$api";
        } else {
            $endpoint = "$service.$ns.$api";
        }


        $body = [
            'endpoint' => $endpoint,
            'metadata' => $metadata,
        ];

        if (isset($args['body']) && is_array($args['body'])) {
            $body = array_merge($body, $args);
        } else {
            $body['body'] = $args;
        }
        return $this->client->post('/', [
            'headers' => [
                'Content-Type' => 'application/json',
                'Cookie' => 'XDEBUG_SESSION=PHPSTORM',
            ],
            'body' => json_encode($body),
        ]);
    }

//    private function getRestfulApiDetail(string $path)
//    {
//        foreach ($this->apis as $apiDetail) {
//            if ($apiDetail['type'] === 'RESTFul') {
//                if ($apiDetail['pathParsed']['type'] === 'normal') {
//                    if ($apiDetail['path'] === $path) {
//                        return $apiDetail;
//                    }
//                } else {
//                    if (preg_match($apiDetail['pathParsed']['pattern'], $path)) {
//                        return $apiDetail;
//                    }
//                }
//            }
//        }
//
//        return null;
//    }
}